<!--
 * Description: FD Summary
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/11/20 11:10
-->

<template>
  <div class="fd-summary" style="margin-top: 10px">
    <div class="select-area">
      <div class="x-prop">
        <el-select v-model="xPropList" clearable filterable multiple style="width: 560px">
          <el-option
            v-for="item in selectProps"
            :key="item.prop"
            :label="item.label"
            :value="item.prop"
          />
        </el-select>
        <el-button style="margin-left: 30px" type="danger" @click="clear('x')">Clear</el-button>
        <el-button type="primary" @click="generate">Generate</el-button>
        <el-button type="success">Download</el-button>
      </div>
      <div class="y-prop">
        <el-select v-model="yPropList" clearable filterable multiple style="width: 560px">
          <el-option
            v-for="item in selectProps"
            :key="item.prop"
            :label="item.label"
            :value="item.prop"
          />
        </el-select>
        <el-button style="margin-left: 30px" type="danger" @click="clear('y')">Clear</el-button>
      </div>
    </div>
    <div v-if="tableData.length > 0" class="table-area">
      <VirtualTable
        childrenAlisas="children"
        :header-cell-style="$headerCellStyle"
        :table="tableData"
        treeIcon="triangle"
      >
        <!-- 层级 -->
        <Cell
          v-for="(item, index) in cellList"
          :key="index"
          :align="index === 0 ? 'left' : 'center'"
          :label="item.label"
          :prop="`summary.${item.prop}`"
        />
      </VirtualTable>
    </div>
  </div>
</template>

<script>
import Cell from '@/widgets/VirtualTable/Cell'
import VirtualTable from '@/widgets/VirtualTable/Table'
export default {
  name: 'FdSummary',

  components: {
    Cell,
    VirtualTable
  },

  props: {
    filterProps: {
      type: Array,
      default: () => []
    },

    shareDataList: {
      type: Array,
      default: () => []
    }
  },

  data() {
    return {
      xPropList: [],

      yPropList: [],

      allProps: [
        {
          label: 'RD Function',
          prop: 'rdFunction'
        },
        {
          label: 'Category',
          prop: 'category'
        },
        {
          label: 'ItemNo',
          prop: 'itemNo'
        },

        {
          label: 'RD Owner',
          prop: 'rdOwner'
        },
        {
          label: 'Tracking&Option',
          prop: 'trackingOption'
        },
        {
          label: 'Part Name(Base)',
          prop: 'basePartName'
        },

        {
          label: 'Part Number(Base)',
          prop: 'basePartNo'
        },
        {
          label: 'Part Description(Base)',
          prop: ' basePartDesc'
        },
        {
          label: 'Material Type(Base)',
          prop: 'baseMaterialType'
        },
        {
          label: 'Material Color(Base)',
          prop: 'baseMaterialColor'
        },
        {
          label: 'Size(Base)',
          prop: 'baseSize'
        },
        {
          label: 'Qty(Base)',
          prop: 'baseQty'
        },
        {
          label: 'ID Process(Base)',
          prop: 'baseIdProcess'
        },
        {
          label: 'Supplier(Base)',
          prop: 'baseSupplier'
        },
        {
          label: 'Supplier PN(Base)',
          prop: 'baseSupplierPn'
        },
        {
          label: 'Remarks(Base)',
          prop: 'baseRemark'
        },
        {
          label: '采购价(Base)',
          prop: 'baseSapPurchasePrice'
        },
        {
          label: '标准价(Base)',
          prop: 'baseSapStandardPrice'
        },
        {
          label: 'Part Name(New)',
          prop: 'newPartName'
        },
        {
          label: 'Part Number(New)',
          prop: 'newPartNo'
        },
        {
          label: 'Temp Code(New)',
          prop: 'newTempPartNo'
        },
        {
          label: 'Part Description(New)',
          prop: 'newPartDesc'
        },
        {
          label: 'Material Type(New)',
          prop: 'newMaterialType'
        },
        {
          label: 'Material Color(New)',
          prop: 'newMaterialColor'
        },
        {
          label: 'Size(New)',
          prop: 'newSize'
        },
        {
          label: 'Qty(New)',
          prop: 'newQty'
        },
        {
          label: 'ID Process(New)',
          prop: 'newIdProcess'
        },
        {
          label: 'Supplier(New)',
          prop: 'newSupplier'
        },
        {
          label: 'Supplier PN(New)',
          prop: 'newSupplierPn'
        },
        {
          label: 'New Tooling',
          prop: 'newTooling'
        },
        {
          label: 'Remarks(New)',
          prop: 'newRemark'
        },
        {
          label: '采购价(New)',
          prop: 'newSapPurchasePrice'
        },
        {
          label: '标准价(New)',
          prop: 'newSapStandardPrice'
        },
        {
          label: 'Status Compare',
          prop: 'statusCompare'
        },
        {
          label: 'GAP Type',
          prop: 'gapType'
        },
        {
          label: 'GAP Reason',
          prop: 'gapReason'
        },
        {
          label: 'GCM Function',
          prop: 'gcmFunction'
        },
        {
          label: 'Commodity',
          prop: 'commodity'
        },
        {
          label: 'GCM Owner',
          prop: 'gcmOwner'
        },
        // {
        //   label: 'GCM Cost',
        //   prop: 'gcmCost'
        // },
        {
          label: 'GCM Total Cost Delta',
          prop: 'gcmTotalCostDelta'
        },
        {
          label: 'GCM Cost Remark',
          prop: 'gcmCostRemark'
        },

        {
          label: 'Base Price',
          prop: 'basePrice'
        },
        {
          label: 'Option Type',
          prop: 'optionType'
        },
        {
          label: 'PBM Total Cost Delta',
          prop: 'pbmTotalCostDelta'
        },
        {
          label: 'PBM Commit Total Cost Delta',
          prop: 'pbmCommitTotalCostDelta'
        }
        // {
        //   label: 'Pir Delta',
        //   prop: 'priDelta'
        // },
        // {
        //   label: 'Tec Delta',
        //   prop: 'tecDelta'
        // },
        // {
        //   label: 'Auc Delta',
        //   prop: 'aucDelta'
        // }
      ],

      cellList: [],

      tableData: []
    }
  },

  computed: {
    selectProps() {
      if (this.filterProps.length === 0) {
        return this.$deepCopy(this.allProps)
      } else {
        return this.allProps.filter(item => this.filterProps.findIndex(p => p === item.prop) === -1)
      }
    }
  },

  methods: {
    clear(type) {
      if (type === 'x') {
        this.xPropList = []
      } else {
        this.yPropList = []
      }
    },

    generate() {
      const tempList = []

      const xyPropList = this.xPropList.concat(this.yPropList)

      // 需要显示的属性
      this.cellList = xyPropList.map(item => {
        return this.allProps.find(p => item === p.prop)
      })

      this.xPropList.forEach((item, index) => this.group({ depth: index, tempList }))
      // 求和、属性赋值
      this.summary(tempList)
      // 生成树
      this.makeTree(tempList)
      // 过滤
      this.tableData = tempList.filter(item => item.depth === 0)
    },

    makeTree(list = []) {
      for (let i = 0, len = list.length; i < len; i++) {
        const currentItem = list[i]
        if (currentItem.depth === 0) {
          continue
        } else {
          this.searchParent(currentItem, list)
        }
      }
    },

    searchParent(node, list = []) {
      const parentNode = list.find(
        currentItem =>
          node.parentPropName === currentItem.currentPropName &&
          node.parentPropValTotal === currentItem.currentPropValTotal
      )

      if (parentNode) {
        if (parentNode.children) {
          // 之前是否数组中是否已经存在
          const isExist = parentNode.children.find(
            currentItem =>
              node.currentPropName === currentItem.currentPropName &&
              node.currentPropValTotal === currentItem.currentPropValTotal
          )
          if (!isExist) {
            parentNode.children.push(node)
          }
        } else {
          parentNode.children = [node]
        }
        if (parentNode.deptp !== 0) {
          this.searchParent(parentNode, list)
        }
      }
    },

    group({ depth, tempList = [] }) {
      for (let i = 0, len = this.shareDataList.length; i < len; i++) {
        const currentItem = this.shareDataList[i]

        const currentPropName = this.xPropList[depth]
        const currentPropVal = currentItem[currentPropName]
        const currentPropValTotal = this.joinPropVal(
          currentItem,
          this.xPropList.slice(0, depth + 1)
        )

        const parentPropName = this.xPropList[depth - 1] ? this.xPropList[depth - 1] : 0
        const parentPropValTotal = this.joinPropVal(currentItem, this.xPropList.slice(0, depth))

        const { isExist, index } = this.isExist(currentPropValTotal, tempList)
        if (!isExist) {
          tempList.push({
            id: currentPropValTotal,
            depth,
            currentPropName,
            currentPropVal,
            currentPropValTotal,
            parentPropName,
            parentPropValTotal,
            data: [currentItem]
          })
        } else {
          tempList[index].data.push(currentItem)
        }
      }
    },

    // 根据depth遍历出每级的propVal
    joinPropVal(currentItem, list = []) {
      return list.map(item => currentItem[item]).join('|||')
    },

    // 目标数组中是否已经存在
    isExist(currentPropValTotal, tempList = []) {
      const index = tempList.findIndex(item => item.currentPropValTotal === currentPropValTotal)
      return index === -1 ? { isExist: false, index: -1 } : { isExist: true, index: index }
    },

    summary(list = []) {
      list.forEach((item, index) => {
        const summary = {}
        this.yPropList.forEach(yPropName => {
          summary[yPropName] = item.data.reduce((total, cur) => {
            return total + cur[yPropName]
          }, 0)
        })
        this.xPropList.forEach((xPropName, index) => {
          if (index > item.depth) return
          summary[xPropName] = item.currentPropValTotal.split('|||')[index]
          // if (xPropName === item.currentPropName) {
          //   summary[xPropName] = item.currentPropVal
          // } else {
          //   summary[xPropName] = ''
          // }
        })
        item.summary = summary
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.fd-summary {
  position: fixed;
  top: 68px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  padding: 25px 25px 16px 20px;
}

.select-area {
  height: 130px;
  overflow-y: auto;
  .x-prop {
    margin-top: 10px;
  }
  .y-prop {
    margin-top: 10px;
  }
}

.table-area {
  height: calc(100% - 130px);
}
</style>
